#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


# https://github.com/honguyenminh/Mod7KeyGen
# https://www.betaarchive.com/forum/viewtopic.php?t=25550



    def use_default_product_key(self):
        assert self.product_key is None

        if self.edition == Edition.WINDOWS_XP_HOME:
            # ?
            return "NG4HW-VH26C-733KW-K6F98-J8CK4"

        if self.arch == Arch.X86 and self.edition == Edition.WINDOWS_XP_PROFESSIONAL:
            # ?
            return "HCQ9D-TVCWX-X9QRG-J4B2Y-GR2TT"

        if self.arch == Arch.X86_64 and self.edition == Edition.WINDOWS_XP_PROFESSIONAL:
            # ?
            return "B66VY-4D94T-TPPD4-43F72-8X4FY"

        assert False



class ProductKeyUtil:

    @classmethod
    def check_product_key(cls, keyin):
        if len(keyin) == 11:             # eg. yol-1111111 and yolo1111111
            cls._checkRetailKey(keyin)
        elif len(keyin) == 23:           # eg. 19996-OEM-7215850f12345
            if "-OEM-" in keyin:
                cls._checkOemKey(keyin)
            else:
                raise KeyError("invalid OEM key")
        else:
            raise KeyError("invalid key length")

    @classmethod
    def _checkRetailKey(keyin):
        digi1, digi2, digi3, digi4, digi5, digi6, digi7, digi8, digi9, digi10, digi11 = keyin
    
        # check the first 3 numbers for obvious fakes / blacklisted.
        # missing 111 and 222 for some reason.
        try:
            checkFirst = int(digi1 + digi2 + digi3)
            if checkFirst in (333, 444, 555, 666, 777, 888, 999):
                raise KeyError("invalid key prefix")
        except ValueError:
            raise KeyError("invalid key prefix")

        # as we enterd a string, convert it to a int to we can math it.
        digi5  = int(digi5)
        digi6  = int(digi6)
        digi7  = int(digi7)
        digi8  = int(digi8)
        digi9  = int(digi9)
        digi10 = int(digi10)
        digi11 = int(digi11)

        # divide the sum by the char length. as we can only enter 7 then its just 7.
        keyin = digi5 + digi6 + digi7 + digi8 + digi9 + digi10 + digi11
        keyweight = keyin / 7
        keycheck = keyin % 7

        # if the modulo opt of keycheck returns a whole number, no remainders then its a legit key.
        if keycheck != 0:
            raise KeyError("invalid key.")

    @classmethod
    def _checkOemKey(keyin):
        # unpack the key into veribiles.
        # yes, this looks and is retrated.
        digi1, digi2, digi3, digi4, digi5, digi6, digi7, digi8, digi9, digi10, digi11, digi12, digi13, digi14, digi15, digi16, digi17, digi18, digi19, digi20, digi21, digi22, digi23 = keyin
        # 1     9      9      9      6      -      O      E      M      -       0       3       1       3       9       8       4       -       1       2       3       4       5

        # date check
        checkday  = int(digi1 + digi2 + digi3)
        checkyear = int(digi4 + digi5)
        dayrange  = range(1, 367)
        yearlist  = [95, 96, 97, 98, 99, 0, 1, 2]

        # crappy date check, should be done with one function but its bugging out.
        if not checkday in dayrange:
            raise KeyError("fail date check, out of range day")
        if not checkyear in yearlist:
            raise KeyError("fail date check, out of range year")

        digi11 = int(digi11)
        digi12 = int(digi12)
        digi13 = int(digi13)
        digi14 = int(digi14)
        digi15 = int(digi15)
        digi16 = int(digi16)
        digi17 = int(digi17)

        # leading 0 check
        if not digi11 == 0 or digi18 != '-':
            raise KeyError("key formatting error, no Leading zero or missing the 3rd -")
    
        sum7 = digi11 + digi12 + digi13 + digi14 + digi15 + digi16 + digi17
        if sum7 == 0000000:
            raise KeyError("OEM Key can not be all 0's")
    
        keyweight = sum7 / 7
        mod7    = sum7 % 7
    
        # check if the last random part of the key is numbers and not letters
        try:
            checkint = int(digi19 + digi20 + digi21 + digi22 + digi23)
        except ValueError:
            raise KeyError("product key must be a number")
    
        if mod7 != 0:
            raise KeyError("invalid key")
